<?php


namespace App\Logic\Account\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Logic\Member\MemberProfitScoreService;
use App\Logic\Member\MemberScoreService;
use App\Model\Account\CashoutModel;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Member\MemberScoreModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\ORM\DbManager;

class CancelCashoutForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $remark;
    public $_memberModel;
    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'id'    => ['required|numeric', 'id', 'id错误'],
            'user_id' => ['required|numeric', '用户id', '用户id错误'],
            'remark' => ['required', '取消原因', '取消原因错误'],
        ];
    }
    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        /**通过id获取提现记录*/
        $cashout = CashoutModel::getOne(['id' => $this->id]);
        if(!$cashout){
            throw new DefaultException('提现记录不存在', 600);
        }
        /**判断用户id是否匹配*/
        if($cashout->user_id != $this->user_id){
            throw new DefaultException('用户id不匹配,请核实', 600);
        }
        /**判断当前状态是否为INPROGRESS*/
        if($cashout->cash_state != CashoutModel::INPROGRESS){
            throw new DefaultException('提现记录状态错误', 600);
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            $cashout = CashoutModel::create()->connection('write')->lockForUpdate()->get($this->id);

            $data = [
                'remark'       => $this->remark,
                'cash_state'   => CashoutModel::CANCELLED,
                'payment_date' => date('Y-m-d'),
            ];
            CashoutModel::create()->updateData($data, ['id' => $this->id]);

            /**将提现记录的积分退回给用户*/
            if($cashout->account_type == CashoutModel::ACCOUNT_TYPE_FUNDS) {
                MemberScoreService::getInstance()->change($cashout->user_id, $cashout->amout, MemberScoreModel::TYPE_CASHOUT_CANCEL, $cashout->id, $this->remark);
            }
            elseif ($cashout->account_type == CashoutModel::ACCOUNT_TYPE_PROFIT){
                MemberProfitScoreService::getInstance()->change($cashout->user_id, $cashout->amout, MemberProfitScoreModel::TYPE_CASHOUT_CANCEL, $cashout->id, $cashout->user_id, $this->remark);
            }else{
                throw new DefaultException('提现账户类型错误', 600);
            }
//            $member = MemberModel::create()->getOne(['id' => $cashout->user_id]);
//            if (!$member) {
//                throw new DefaultException('用户不存在', 600);
//            }
//            /**修改member积分*/
//            $data = [
//                'score' => bcadd($member->score, $cashout->amout, 2),
//            ];
//            MemberModel::create()->updateData($data, ['id' => $cashout->user_id]);
//            /**添加积分变动记录MemberScore*/
//            $data = [
//                'user_id'      => $cashout->user_id,
//                'score'        => $cashout->amout,
//                'before_score' => $member->score,
//                'after_score'  => bcadd($member->score, $cashout->amout, 2),
//                'created_date' => date('Y-m-d'),
//                'type'         => MemberScoreModel::TYPE_CASHOUT_CANCEL,
//                'object_id'    => $cashout->id,
//                'remark'       => $this->remark,
//            ];
//            MemberScoreModel::create()->insertData($data);

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $this->id];
            $result     = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }

}
